package com.hksj.Intelligentmanagement.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;

public class ExportExcelUtil {

    /**
     * 导出表格
     * @param fileName 文件名称
     * @param data 数据
     * @param headerMap 表头别名
     * @param response 响应对象
     */
    public static void export(String fileName,Iterable<?> data,Map<String, String> headerMap,HttpServletResponse response){
        export(null,0,fileName,data,headerMap,response,null);
    }

    /**
     * 导出表格
     * @param templatePath 模板文件路径
     * @param skipRows 跳过行数
     * @param fileName 文件名称
     * @param data 数据
     * @param headerMap 表头别名
     * @param response 响应对象
     */
    public static void export(String templatePath, Integer skipRows, String fileName, Iterable<?> data, Map<String, String> headerMap, HttpServletResponse response, ExportExcelHandler handler){
        //初始化表格写对象
        ExcelWriter writer = null;
        File templateXlsx = loadTemplate(templatePath);
        //有模板获取模板
        if (!Objects.isNull(templateXlsx)){
            writer = ExcelUtil.getWriter(templateXlsx);
        }else {
            //没有模板创建默认表格
            writer = ExcelUtil.getWriter(true);
        }
        //设置单元格自动换行
        StyleSet style = writer.getStyleSet();
        style.setWrapText();
        writer.setHeaderAlias(headerMap);
        writer.setOnlyAlias(true);

        //跳过标题
        writer.passRows(skipRows);
        //不输出表头
        writer.write(data,false);
        //回调做一些附加处理
        if (ObjectUtil.isNotEmpty(handler)){
            handler.handle(writer);
        }

        //导出
        ServletOutputStream out = null;
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            writer.close();
            IoUtil.close(out);
            FileUtil.del(templateXlsx);
        }
    }

    public static File loadTemplate(String templatePath){
        FileOutputStream out = null;
        ExcelWriter writer = null;
        File tempFile = null;
        if (StrUtil.isNotBlank(templatePath)){
            try {
                //获取模板文件
                File file = FileUtil.file(templatePath);
                if (!file.exists()){
                    file = FileUtil.file(file.getAbsolutePath().replace("app.jar!/BOOT-INF/classes!","BOOT-INF/classes"));
                }
                //创建临时文件
                //1.获取路径
                String tempFilePath = "";
                if (templatePath.endsWith(".xlsx")){
                    tempFilePath = file.getAbsolutePath().replace(".xlsx","_tmp.xlsx");
                }else if(templatePath.endsWith(".xls")){
                    tempFilePath = file.getAbsolutePath().replace(".xls","_tmp.xls");
                }
                //2.创建文件
                tempFile = FileUtil.file(tempFilePath);
                if (!tempFile.exists()){
                    tempFile.createNewFile();
                }
                out = new FileOutputStream(tempFile);
                writer = ExcelUtil.getWriter(file);
                writer.flush(out,true);
            }catch (Exception e){
                throw new RuntimeException(e);
            }finally {
                if (!ObjectUtil.isEmpty(writer)){
                    writer.close();
                }
                if (!ObjectUtil.isEmpty(out)){
                    IoUtil.close(out);
                }
            }
        }
        return tempFile;
    }
}
